import axios from 'axios'
import qs from 'qs'
import { BASE_URL, NOT_HAS_BASE } from './config'
import { getToken } from '@/utils/auth'

// // axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';        //配置请求头

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: BASE_URL,
  timeout: 60000,
})

//POST传参序列化(添加请求拦截器)
service.interceptors.request.use(
  (config) => {
    // //在发送请求之前做某件事 是否需要设置 token
    let isToken = (config.headers || {}).isToken === false
    // console.log('请求??')
    if (config.url == '/captchaImage' || config.url == '/login') {
      isToken = true
    }
    if (getToken() && !isToken) {
      config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    } else {
    }

    return config
  },
  (error) => {
    // console.log('错误的传参')
    return Promise.reject(error)
  }
)

//返回状态判断(添加响应拦截器)
service.interceptors.response.use(
  (res) => {
    //对响应数据做些事
    if (!res.data.success) {
      return Promise.resolve(res.data)
    }
    return res
  },
  (error) => {
    // console.log('网络异常')
    return Promise.reject(error)
  }
)

//返回一个Promise(发送post请求)
export function post(url, params) {
  return new Promise((resolve, reject) => {
    service
      .post(url, params)
      .then(
        (response) => {
          resolve(response)
        },
        (err) => {
          reject(err)
        }
      )
      .catch((error) => {
        reject(error)
      })
  })
}
////返回一个Promise(发送get请求)
export function get(url, params) {
  return new Promise((resolve, reject) => {
    service
      .get(url, { params })
      .then(
        (response) => {
          resolve(response)
        },
        (err) => {
          reject(err)
        }
      )
      .catch((error) => {
        reject(error)
      })
  })
}

export default {
  post,
  get,
}
